package xxm.utility;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

import xxm.exception.UtilityException;

/**
 * Properties manager
 * @author xxm
 *
 */
public class BasicPropertiesManager extends Properties {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2122858854767485186L;
	private Properties config = null;
	private static BasicPropertiesManager manager = null;
	
	public BasicPropertiesManager() {
	
	}
	
	/**
	 * init Properties
	 * @param propertyFile  :Properties file 
	 * @throws UtilityException
	 */
	public void initProperties( final String propertyFile ) throws UtilityException {
		try {
			if( !BasicUtility.checkFileExists(propertyFile) ) {
				return;
			}
			InputStream in = new BufferedInputStream(new FileInputStream(propertyFile));
			config = new Properties();
			config.load(in);
			in.close();
		} catch (IOException e) {
			throw new UtilityException("BasicPropertiesManager initProperties",e);
		}
	}
	
	/**
	 * get instance
	 * @return
	 */
	public static BasicPropertiesManager GetInstance() {
		if( manager == null ) {
			manager = new BasicPropertiesManager();
		}
		return manager;
	}
	
	/**
	 * read value by key 
	 * @param key
	 * @return
	 * @throws UtilityException
	 */
	public String readValue(String key) throws UtilityException{
		// Properties props = new Properties();
		try {
			if( config == null ) {
				return null;
			}
			String value = config.getProperty(key);
			return value;
		} catch (Exception e) {
			throw new UtilityException("BasicPropertiesManager readValue",e);
		}
	}

	/**
	 * read all properties info
	 * @throws UtilityException
	 */
	public void readAllProperties()throws UtilityException {
		try {
			if( config == null ) {
				return ;
			}
			Enumeration en = config.propertyNames();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				String Property = config.getProperty(key);
				//System.out.println(key +" "+ Property);
			}
		} catch (Exception e) {
			throw new UtilityException("BasicPropertiesManager readAllProperties",e);
		}

	}
}
